package ps.client.plugin.eq2.gui.dialog.curses;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

import ps.client.plugin.eq2.gui.dialog.curses.timer.TimerEvent;
import ps.client.plugin.eq2.gui.dialog.curses.timer.TimerListener;


@SuppressWarnings("serial")
public class CurseComponent extends JPanel implements TimerListener {
	
	JLabel label = new JLabel();
	CountdownPanel countdownPanel;
	
	String name;
	int timerSecs;
	int warningSecs = 5;
	
	long lastPressed = -1;
	
	
	public CurseComponent(String name, int timer) {
		this.name = name;
		this.timerSecs = timer;
		
		countdownPanel = new CountdownPanel(timer);
		
		label.setText(name);
		label.setFont(new Font("Arial", Font.PLAIN, 18));
//		label.setBorder(new EmptyBorder(2, 6, 2, 4));
		label.setBorder(new EmptyBorder(1, 4, 1, 3));
		countdownPanel.getTimer().start();
		countdownPanel.setBorder(new EmptyBorder(2, 2, 0, 4));
		countdownPanel.setBackground(Color.RED);
		
		setBackground(Color.RED);
		setMinimumSize(new Dimension(100, 30));
		setMaximumSize(new Dimension(400, 30));
		setBorder(new LineBorder(Color.BLACK, 1, false));
		addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON1) {
					if (lastPressed > 0) {
						if (System.currentTimeMillis() - lastPressed < 400) {
						    fireDoubleClick();
							lastPressed = -1;	
						}
					}
					lastPressed = System.currentTimeMillis();
					e.consume();
				}
			}
		});
		
		setLayout(new BorderLayout());
		add(label, BorderLayout.CENTER);
		add(countdownPanel, BorderLayout.EAST);
		
		countdownPanel.getTimer().addTimerListener(this);
	}
	
	public void timerEvent(TimerEvent e) {
		if (e.getSecs() >= timerSecs) {
			setBackground(Color.GREEN);
			countdownPanel.setBackground(Color.GREEN);
		} else if (e.getSecs() >= timerSecs - warningSecs) {
			setBackground(Color.YELLOW);
			countdownPanel.setBackground(Color.YELLOW);
		} else if (e.getSecs() < timerSecs) {
			setBackground(Color.RED);
			countdownPanel.setBackground(Color.RED);
		}
	}
	
	public void setTimer(int secs) {
	    timerSecs = secs;
	    countdownPanel.setTimer(secs);
	}
	
	public void resetTimer() {
	    setBackground(Color.RED);
        countdownPanel.setBackground(Color.RED);
		countdownPanel.getTimer().restart();
	}
	
	public void setTimerToZero() {
	    countdownPanel.setLeftSecsToZero();
	    setBackground(Color.GREEN);
        countdownPanel.setBackground(Color.GREEN);
	}
	
	public String getName() {
	    return name;
	}
	
	protected void fireDoubleClick() {
	}

}
